package com.incar.chuxing.activity;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.incar.chuxing.R;
import com.incar.chuxing.adapter.ParkDetailPagerAdapter;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.UrlConstant;
import com.incar.chuxing.baiduMap.GeoCoderUtils;
import com.incar.chuxing.baiduMap.LocationFilter;
import com.incar.chuxing.baiduMap.MarkerUtils;
import com.incar.chuxing.baiduMap.PolygonUtils;
import com.incar.chuxing.baiduMap.RoutePlan;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.CityBoundBean;
import com.incar.chuxing.bean.PopPostBean;
import com.incar.chuxing.bean.QualificationBean;
import com.incar.chuxing.bean.TopMesBean;
import com.incar.chuxing.bean.CancelOrder;
import com.incar.chuxing.bean.CheckCarOrderBean;
import com.incar.chuxing.bean.CityDetailBean;
import com.incar.chuxing.bean.InitBean;
import com.incar.chuxing.bean.MsgRedBean;
import com.incar.chuxing.bean.NearParkOrCarBean;
import com.incar.chuxing.bean.OperateBean;
import com.incar.chuxing.bean.TravelDetailBean;
import com.incar.chuxing.bean.MapParksAndCarsBean;
import com.incar.chuxing.bean.ParkDetailBean;
import com.incar.chuxing.bean.ResultBean;
import com.incar.chuxing.bean.ExistingTravel;
import com.incar.chuxing.baiduMap.MapStatusUtils;
import com.incar.chuxing.utils.AccountStatus;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.Constants;
import com.incar.chuxing.utils.DataBeanConvert;
import com.incar.chuxing.utils.DensityUtils;
import com.incar.chuxing.utils.Dialogs.UnFinishTravelDialog;
import com.incar.chuxing.utils.ImageLoader;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.IntentUtils;
import com.incar.chuxing.utils.Dialogs.InCarDialog;
import com.incar.chuxing.utils.MyApplication;
import com.incar.chuxing.utils.SharedPreferencesKey;
import com.incar.chuxing.utils.SharedPreferencesUtils;
import com.incar.chuxing.utils.TimeUtils;
import com.incar.chuxing.utils.Toast.ToastCompat;
import com.incar.chuxing.utils.Dialogs.UserHelpDialog;
import com.incar.chuxing.widget.MyViewPager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.IUmengCallback;
import com.umeng.message.PushAgent;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.baidu.location.BDLocation.TypeCriteriaException;
import static com.baidu.location.BDLocation.TypeNetWorkException;
import static com.baidu.location.BDLocation.TypeNetWorkLocation;
import static com.baidu.location.BDLocation.TypeServerError;


/**
 * 地图方法说明
 * 1.定位结果：        {@link MyLocationListener#onReceiveLocation(BDLocation)} (AMapLocation)}
 * 2.Marker点击回调：  {@link #initMap()}
 * 3.单车、汽车切换：   {@link #clearMap(boolean)}   清除地图和遮盖的布局
 * 4.路线规划：        RoutePlan.getInstance().startRoutePlan(...) 地图只能显示单条路线，回调返回距离时间
 * 5.清空地图         {@link MapStatusUtils#clearMap()}        如以后在地图上添加其他的内容，需要在此方法中添加清除该内容的代码
 * 6.清除路线         {@link RoutePlan#clearRoutePlanning()} ()}
 * 7.清除单车和汽车Marker   {@link MarkerUtils#clearParksAndCarsMarker()} ()}
 */

public class MainActivity extends BaseActivity implements SensorEventListener {
    private Context mContext = this;
    private TextView tv_address_no_car, tv_distance_no_car, tx_reserve_order_timer,
            tx_place_order_remind1, tx_place_order_remind2, tx_place_order_brand, tx_place_order_plate,
            tv_place_order_remark, tx_place_order_position, textView_order_cancel, textView_rent, no_car_near, park_fee_tips_main;
    private ImageView gift_mainActivity, mes_red_hot, gift_red_hot, iv_order_car, imageView_help,
            imageView_locate, imageView_refresh;
    private RelativeLayout layout_park_detail, layout_no_car;
    private LinearLayout layout_reserve_order;
    private LinearLayout use_car_layout;
    private RadioGroup radioGroup;
    private RadioButton[] arrRadioButton = null;
    private MyViewPager pagerParkDetail;
    private MapView mapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocClient;
    public MyLocationListener myListener = new MyLocationListener();
    private SensorManager mSensorManager;
    private static MarkerUtils markerUtils;
    private MapStatusUtils mapStatusUtils;
    private PolygonUtils polygonUtils;
    private int mCurrentDirection = 0;
    private MyLocationData locData;
    private float mCurrentAccracy;
    public LatLng curPosition;
    private String address;
    private boolean isFirstLocationError = true;
    private int locationErrorCode;
    private Double lastX = 0.0;
    private ParkDetailPagerAdapter pagerAdapter;
    private int choosePosition = 0;

    private boolean isFirstInMain = true;   //第一次进入主页面
    private boolean isLoadingDone = false;
    private boolean isExit = false;
    private boolean isAnimatorShow = false;
    private Boolean isFirstLocation = true;

    private String orderId;
    private String carId;
    private String parkId;
    private String carLicense;
    private CountDownTimer timer;
    private float layoutHeight = 0F;
    //private AnimatorSet animSet;
    private PowerManager.WakeLock wakeLock;
    private String model = android.os.Build.MODEL;
    private long adLatestTime;
    private Map<String, String> notifyMap = new HashMap<>();
    private List<MapParksAndCarsBean.AttachmentBean.CarModelsBean> carsList = new ArrayList<>();
    private List<ParkDetailBean.AttachmentBean.CarsBean> totalList = new ArrayList<>();
    private List<List<CityBoundBean.AttachmentBean>> cityBoundsInfo;

    @Override
    public void initCustomMapView() {
        // new MapStatusUtils().setMapCustomFile(this, "custom_config.json");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {
        //EventBus.getDefault().register(this);           //注册EventBus
        PushAgent.getInstance(this).enable(new IUmengCallback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });
    }

    @Override
    public void initView() {
        initMainView();
        initMainLayout();
        initMap();
        initLocationService();
    }

    private void initMainLayout() {
        initParkDetailLayout();
        initReserveOrderLayout();
        initNoCarLayout();
    }

    //提示打开定位服务
    private void initLocationService() {
  /*      if (SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) == null) {
            ObjectAnimator animator = ObjectAnimator.ofFloat(imageView_help, "translationY", DensityUtils.dp2px(mContext, 0), DensityUtils.dp2px(mContext, 173));
            animator.setDuration(800).setInterpolator(new BounceInterpolator());
            animator.start();
        }*/
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // 判断定位服务是否开启，如果没有则开启
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            final InCarDialog inCarDialog = new InCarDialog(this);
            inCarDialog.setTitle(getString(R.string.dialogTitle));
            inCarDialog.setMessage(getString(R.string.LocationServiceRemind));
            inCarDialog.setYesOnclickListener("去设置", new InCarDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, Constants.REQUEST_Location_Service);
                    inCarDialog.dismiss();
                }
            });
            inCarDialog.setNoOnclickListener("取消", new InCarDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    inCarDialog.dismiss();
                }
            });
            inCarDialog.setCanceledOnTouchOutside(true);
            inCarDialog.setCancelable(true);
            inCarDialog.show();
        }
    }

    //初始化地图
    public void initMap() {
        mapView = (MapView) findViewById(R.id.map_mainActivity);
        mapView.showZoomControls(false);
        //MapView.setMapCustomEnable(true);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        if (mBaiduMap == null) {
            mBaiduMap = mapView.getMap();
            //设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            mBaiduMap.setMyLocationEnabled(false);
            // 开启定位图层
            mBaiduMap.setMyLocationEnabled(true);
            mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                    MyLocationConfiguration.LocationMode.NORMAL, true,
                    BitmapDescriptorFactory.fromResource(R.drawable.icon_mylocation)));
            //设置地图交互
            UiSettings uiSettings = mBaiduMap.getUiSettings();
            uiSettings.setRotateGesturesEnabled(false);
            uiSettings.setOverlookingGesturesEnabled(false);
            uiSettings.setZoomGesturesEnabled(true);
            // 定位初始化
            mLocClient = new LocationClient(this);
            LocationClientOption option = new LocationClientOption();
            option.setIsNeedAddress(true);
            option.setIsNeedLocationDescribe(true);
            option.setOpenGps(true); // 打开gps
            option.setCoorType("bd09ll"); // 设置坐标类型
            option.setScanSpan(5000);
            mLocClient.setLocOption(option);
            mLocClient.registerLocationListener(myListener);

            markerUtils = new MarkerUtils(mBaiduMap, mContext);
            mapStatusUtils = new MapStatusUtils(mBaiduMap);
            mapStatusUtils.defaultPosition();
            polygonUtils = new PolygonUtils(mBaiduMap);
            mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
                @Override
                public void onMapClick(com.baidu.mapapi.model.LatLng latLng) {
                    backPress(false);
                }

                @Override
                public boolean onMapPoiClick(MapPoi mapPoi) {
                    return false;
                }
            });
            mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(final Marker marker) {
                    //获取附加在marker中的数据
                    Bundle markerInfoBundle = marker.getExtraInfo();
                    if (!layout_reserve_order.isShown()) {
                        //根据parkId显示网点的详情，或者只显示一个车辆的详情
                        RoutePlan.getInstance().clearRoutePlanning();
                        if (markerInfoBundle.getInt("carOrPark") == 0) { //标识marker是网点还是汽车 0网点  1汽车
                            showParkDetailLayout(markerInfoBundle.getString("parkId"), markerInfoBundle.getString("parkName"), marker.getPosition());
                        } else if (markerInfoBundle.getInt("carOrPark") == 1) {
                            if (carsList != null && carsList.size() != 0) {
                                showCarDetailLayout(markerInfoBundle.getInt("carMarkerId"), markerInfoBundle.getString("timeStr"), marker);
                            }
                        }
                    }
                    return true;
                }
            });

            mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
                @Override
                public void onMapStatusChangeStart(MapStatus mapStatus) {
                }

                @Override
                public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

                }

                @Override
                public void onMapStatusChange(MapStatus mapStatus) {
                    if (null != cityBoundsInfo) {
                        if (mapStatus.zoom < 16 && polygonUtils.polygonCoverList.size() == 0) {
                            polygonUtils.addBoundsCover(cityBoundsInfo);  //添加城市围栏填充色
                        } else if (mapStatus.zoom >= 16 && polygonUtils.polygonCoverList.size() != 0) {
                            polygonUtils.clearCover();   //清除城市围栏填充色
                        }
                    }
                }

                @Override
                public void onMapStatusChangeFinish(MapStatus mapStatus) {

                }
            });

            startLocation();

        }

        showLoadingDialog();
    }


    public void clickView(View view) {
        final Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.use_car:        //一键最近车辆 或扫码取车
                if (AccountStatus.isLogin(mContext)) {  //登录状态
                    if (curPosition != null) {
                        getNearCarOrPark();
                    } else {
                        ToastCompat.makeText(mContext, "正在定位...", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }
                break;
            case R.id.imageView_locate:          //定位
                if (curPosition != null) {
                    mapStatusUtils.animateMove(curPosition, 18, 600);
                } else {
                    ToastCompat.makeText(mContext, "正在定位...", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.imageView_refresh:          //刷新
                markerUtils.clearParksAndCarsMarker();
                //清除普通车路线规划
                RoutePlan.getInstance().clearRoutePlanning();
                if (curPosition != null) {
                    mapStatusUtils.animateMove(curPosition, 18, 600);
                    getParksAndCars();
                } else {
                    ToastCompat.makeText(mContext, "正在定位...", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.imageView_hotline:  //客服
               /* if (AccountStatus.isLogin(mContext)) {
                    MobclickAgent.onEvent(MainActivity.this, Constants.FEEDBACK);
                    intent.setClass(mContext, FeedbackActivity.class);
                    if (layout_reserve_order.isShown()) {
                        if (orderId != null) {
                            intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                        }
                        intent.putExtra("licenseTag", carLicense);

                    }
                    startActivity(intent);
                    MobclickAgent.onEvent(MainActivity.this, Constants.HOME_CUSTOMER_SERVICE);
                } else {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }*/
                break;
            case R.id.myInfo_mainActivity:      //个人中心
                if (!AccountStatus.isLogin(mContext)) {//未登录
                    intent.setClass(mContext, LoginActivity.class);
                    startActivity(intent);
                } else if (layout_reserve_order == null || !layout_reserve_order.isShown()) {
                    intent.setClass(mContext, PersonalCenterActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.gift_mainActivity: { // 活动
                MobclickAgent.onEvent(MainActivity.this, Constants.ACTIVITY_CENTER);
                gift_red_hot.setVisibility(View.GONE);
                SharedPreferencesUtils.getInstance(mContext).putLongValue("adLatestTime", adLatestTime);
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlConstant.Request.GIFT_URL + "?citycode=" + ((MyApplication) getApplication()).getAreaCode());
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "活动中心");
                startActivity(intent);
            }
            break;
            case R.id.imageView_help: //使用帮助 小绿叶
                imageView_help.setVisibility(View.GONE);
                UserHelpDialog userHelpDialog = new UserHelpDialog(mContext);
                userHelpDialog.show();
                break;
        }
    }

    private void initMainView() {
        imageView_help = (ImageView) findViewById(R.id.imageView_help);
        gift_mainActivity = (ImageView) findViewById(R.id.gift_mainActivity);
        imageView_locate = (ImageView) findViewById(R.id.imageView_locate);
        imageView_refresh = (ImageView) findViewById(R.id.imageView_refresh);
        use_car_layout = (LinearLayout) findViewById(R.id.use_car_layout);
        gift_red_hot = (ImageView) findViewById(R.id.gift_red_hot);
        mes_red_hot = (ImageView) findViewById(R.id.mes_red_hot);
        park_fee_tips_main = (TextView) findViewById(R.id.park_fee_tips_main);
        /*//弹出海报消失后礼物按钮的动画
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(gift_mainActivity, "rotation", 0, 30, 0, -30, 0);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(gift_mainActivity, "translationX", 0, 5, 0, -5, 0);
        animSet = new AnimatorSet();
        animSet.setDuration(250);
        animSet.setInterpolator(new LinearInterpolator());
        animSet.playTogether(anim1, anim2);
*/
    }

    //初始化网点车辆弹出布局,从列表选择，一键选车，点击图标弹出的布局
    private void initParkDetailLayout() {
        layout_park_detail = (RelativeLayout) findViewById(R.id.layout_park_detail);
        pagerParkDetail = (MyViewPager) findViewById(R.id.viewPager_parkDetail);
        pagerAdapter = new ParkDetailPagerAdapter(mContext, totalList);
        pagerParkDetail.setAdapter(pagerAdapter);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup_viewPager);
        textView_rent = (TextView) findViewById(R.id.textView_rent);
        pagerParkDetail.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                arrRadioButton[position].setChecked(true);
                choosePosition = position;      //设置viewpager当前选择的position
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        //立即租用按钮监听
        textView_rent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MobclickAgent.onEvent(MainActivity.this, Constants.IMMEDIATE_HIRE_CAR);
                Intent intent = new Intent();
                if (SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) != null) {
                    intent.setClass(mContext, ChooseInsuranceActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("carsBean", pagerAdapter.getItem(choosePosition));
                    intent.putExtras(bundle);
                    startActivityForResult(intent, Constants.REQUEST_RENT);
                } else {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }
            }
        });
    }

    //初始化网点详情viewPager的指示器
    private void initViewPagerDots(int count) {
        if (count == 1) {
            count = 0;
        }
        radioGroup.removeAllViews();
        arrRadioButton = null;
        arrRadioButton = new RadioButton[count];
        for (int i = 0; i < count; i++) {
            RadioButton radioButton = new RadioButton(mContext);
            radioButton.setPadding(25, 0, 25, 0);
            radioButton.setButtonDrawable(R.drawable.dots);
            radioGroup.addView(radioButton);
            arrRadioButton[i] = radioButton;
        }
        if (arrRadioButton.length != 0) {
            arrRadioButton[0].setChecked(true);
        }
    }

    //初始化下单寻车弹出布局
    private void initReserveOrderLayout() {
        layout_reserve_order = (LinearLayout) findViewById(R.id.layout_reserve_order);
        iv_order_car = (ImageView) findViewById(R.id.iv_order_car);
        LinearLayout imageButton_order_find_car = (LinearLayout) findViewById(R.id.imageButton_order_find_car);
        tv_place_order_remark = (TextView) findViewById(R.id.tx_place_order_remark);
        tx_place_order_position = (TextView) findViewById(R.id.tx_place_order_position);
        tx_place_order_brand = (TextView) findViewById(R.id.tx_place_order_brand);
        textView_order_cancel = (TextView) findViewById(R.id.textView_order_cancel);
        tx_place_order_plate = (TextView) findViewById(R.id.tx_place_order_plate);
        tx_reserve_order_timer = (TextView) findViewById(R.id.tx_place_order_timer);
        tx_place_order_remind1 = (TextView) findViewById(R.id.tx_place_order_remind1);
        tx_place_order_remind2 = (TextView) findViewById(R.id.tx_place_order_remind2);
        LinearLayout getImageButton_order_lock_on = (LinearLayout) findViewById(R.id.imageButton_order_lock_on);
        imageButton_order_find_car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                findCar(orderId, carId);
            }
        });
        getImageButton_order_lock_on.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final InCarDialog inCarDialog = new InCarDialog(MainActivity.this);
                inCarDialog.setTitle(getString(R.string.dialogTitle));
                inCarDialog.setMessage(getString(R.string.openCarRemind));
                inCarDialog.setYesOnclickListener("确定", new InCarDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        inCarDialog.dismiss();
                        openCarDoor(orderId, carId);

                    }
                });
                inCarDialog.setNoOnclickListener("取消", new InCarDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        inCarDialog.dismiss();
                    }
                });
                inCarDialog.show();
            }
        });
        textView_order_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final InCarDialog inCarDialog = new InCarDialog(MainActivity.this);
                inCarDialog.setTitle(getString(R.string.dialogTitle));
                inCarDialog.setMessage("每天可取消3次，超出3次则当日无法用车，确定取消订单吗？");
                inCarDialog.setYesOnclickListener("确定", new InCarDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        cancelCarOrder(orderId);
                        inCarDialog.dismiss();
                    }
                });
                inCarDialog.setNoOnclickListener("取消", new InCarDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        inCarDialog.dismiss();
                    }
                });
                inCarDialog.show();
            }
        });
    }


    //初始化无车辆弹出布局
    private void initNoCarLayout() {
        layout_no_car = (RelativeLayout) findViewById(R.id.layout_no_car);
        no_car_near = (TextView) findViewById(R.id.no_car_near);
        tv_address_no_car = (TextView) findViewById(R.id.tv_address_no_car);
        tv_distance_no_car = (TextView) findViewById(R.id.tv_distance_no_car);

        no_car_near.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RoutePlan.getInstance().clearRoutePlanning();
                getNearCarOrPark();
            }
        });
    }

    private void initAppData() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).initApp(((MyApplication) getApplication()).getRequestFieldMap(), model, "1")
                .enqueue(new Callback<InitBean>() {
                    @Override
                    public void onResponse(Call<InitBean> call, final Response<InitBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            InitBean.AttachmentBean attachmentBean = response.body().getAttachment();

                            if (response.body().getStatus() == 200) {
                                InitBean.AttachmentBean result = response.body().getAttachment();
                                ((MyApplication) getApplication()).setHotLine(result.getService_call());
                                ((MyApplication) getApplication()).setImageUrl(result.getImgUrl());
                               /* String versionName = result.getVersionControl().getVersionNum();
                                String forceUpdate = result.getVersionControl().getType() + "";
                                String updateInfo = result.getVersionControl().getUpdateContent();
                                String updateTitle = result.getVersionControl().getUpdateTitle();*/
                                SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.CAR_DAY_TIME, result.getDayTime());
                                SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.CAR_NIGHT_TIME, result.getNightTime());
                                SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.LOTTERY_HISTORY, result.getLotteryHistory());
                              /*  if (isFirstInMain && checkUpdate) {
                                    new VerControlUtils(mContext).update(versionName, forceUpdate, updateInfo, updateTitle);
                                    isFirstInMain = false;
                                }*/
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                                Log.i("statusError", "001");
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<InitBean> call, Throwable t) {
                        ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "001");
                    }
                });
    }

    //弹框海报
    private void getPopPost() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getPopPost(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<PopPostBean>() {
            @Override
            public void onResponse(Call<PopPostBean> call, final Response<PopPostBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment().size() != 0) {
                            adLatestTime = response.body().getAttachment().get(0).getStartTime();
                            Log.i("adLast", SharedPreferencesUtils.getInstance(mContext).getLongValue("adLatestTime") + "");
                            if (adLatestTime > SharedPreferencesUtils.getInstance(mContext).getLongValue("adLatestTime")) {
                                gift_red_hot.setVisibility(View.GONE);
                            }
                           /* if (SharedPreferencesUtils.getInstance(mContext).getIntValue("adPopTime") == 0 || (Calendar.getInstance().get(Calendar.MONTH) + 1) * 100 + Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
                                    != SharedPreferencesUtils.getInstance(mContext).getIntValue("adPopTime")) {*/
                            ArrayList<String> imageList = new ArrayList<>();
                            ArrayList<String> urlList = new ArrayList<>();
                            ArrayList<String> titleList = new ArrayList<>();
                            for (int i = 0; i < response.body().getAttachment().size(); i++) {
                                imageList.add(response.body().getAttachment().get(i).getImgUrl());
                                urlList.add(response.body().getAttachment().get(i).getH5Url());
                                String title = "活动中心";
                                titleList.add(title);
                            }
                            final Intent intent = new Intent(mContext, PopPostActivity.class);
                            intent.putStringArrayListExtra("imageList", imageList);
                            intent.putStringArrayListExtra("urlList", urlList);
                            intent.putStringArrayListExtra("titleList", titleList);
                              /*  intent.putExtra("xLocation", gift_mainActivity.getLeft());
                                intent.putExtra("yLocation", gift_mainActivity.getBottom());*/

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        Glide.with(mContext)
                                                .load(response.body().getAttachment().get(0).getImgUrl())
                                                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                                                .listener(new RequestListener<String, GlideDrawable>() {
                                                    @Override
                                                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                                                        return false;
                                                    }

                                                    @Override
                                                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                                        SharedPreferencesUtils.getInstance(mContext).putIntValue("adPopTime", (Calendar.getInstance().get(Calendar.MONTH) + 1) * 100 + Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
                                                        startActivity(intent);
                                                        return false;
                                                    }
                                                })
                                                .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                                .get();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<PopPostBean> call, Throwable t) {
                ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                Log.i("netError", "003" + t);
            }
        });
    }


    //获取顶部消息及个人中心红点指示
    private void getTopMes() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getTopMes(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<TopMesBean>() {
            @Override
            public void onResponse(Call<TopMesBean> call, final Response<TopMesBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus().equals("200")) {
                        if (response.body().getAttachment() != null) {
                            final List<TopMesBean.AttachmentBean.MessageListBean> messageListBeanList = response.body().getAttachment().getMessageList();
                            List resIds = new ArrayList();
                            for (int i = 0; i < messageListBeanList.size(); i++) {
                                if (messageListBeanList.get(i).getMessageType().equals("4")) {
                                    resIds.add(R.drawable.icon_promote);
                                } else if (messageListBeanList.get(i).getMessageType().equals("3")) {
                                    resIds.add(R.drawable.icon_light);
                                } else {
                                    resIds.add(R.drawable.icon_speaker_color);
                                }
                            }
                        }
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<TopMesBean> call, Throwable t) {
                ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                Log.i("netError", "004" + t);
            }
        });
    }

    //个人中心小红点
    private void getMsgRed() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getMsgRed(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<MsgRedBean>() {
            @Override
            public void onResponse(Call<MsgRedBean> call, final Response<MsgRedBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus().equals("200")) {
                        if (response.body().getAttachment() != null) {
                            mes_red_hot.setVisibility(response.body().getAttachment().getIsRead().equals("1") ? View.VISIBLE : View.GONE);
                        }
                    } else {

                    }
                }
            }

            @Override
            public void onFailure(Call<MsgRedBean> call, Throwable t) {
                ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                Log.i("netError", "003" + t);
            }
        });
    }

    //顶部广告已读
    private void readMessage(String messageId) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).readMsg(((MyApplication) getApplication()).getRequestFieldMap(), messageId).enqueue(new Callback<ResultBean>() {
            @Override
            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                if (((MyApplication) getApplication()).getUid() != null) {
                    getTopMes();
                }
            }

            @Override
            public void onFailure(Call<ResultBean> call, Throwable t) {
            }
        });
    }

    /**
     * 用户进入app或者重新登录后，检查是否有进行中的行程
     * firstCheck true:首次进入app查询是否有进行中订单，false:重新登录后查询未完成订单
     */
    private void hasExistingTravel() {
        showLoadingDialog("正在加载");
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getExistingTravel(((MyApplication) getApplication()).getRequestFieldMap())
                .enqueue(new Callback<ExistingTravel>() {
                    @Override
                    public void onResponse(Call<ExistingTravel> call, final Response<ExistingTravel> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (200 == response.body().getStatus()) {
                                if (response.body().getAttachment().getIsUnfinished() != 0) { //有进行中的行程
                                    orderId = response.body().getAttachment().getOrderId();
                                    switch (response.body().getAttachment().getStatus()) {
                                        case 0:
                                            clearMap(false);
                                            loadCarFindLayout(orderId);
                                            break;
                                        case 10: {
                                            isLoadingDone = true;
                                            clearMap(true);
                                            final UnFinishTravelDialog unFinishTravelDialog = new UnFinishTravelDialog(MainActivity.this);
                                            unFinishTravelDialog.setMessage(getString(R.string.hasInDrivingOrder));
                                            unFinishTravelDialog.setYesOnclickListener("进入", new UnFinishTravelDialog.onYesOnclickListener() {
                                                @Override
                                                public void onYesClick() {
                                                    Intent intentInUse = new Intent(mContext, DrivingActivity.class);
                                                    intentInUse.putExtra(IntentKey.INTENT_ORDER_ID, response.body().getAttachment().getOrderId());
                                                    startActivity(intentInUse);
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setNoOnclickListener("取消", new UnFinishTravelDialog.onNoOnclickListener() {
                                                @Override
                                                public void onNoClick() {
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setCancelable(false);
                                            unFinishTravelDialog.show();
                                        }
                                        break;
                                        case 15: {
                                            isLoadingDone = true;
                                            clearMap(true);

                                            final UnFinishTravelDialog unFinishTravelDialog = new UnFinishTravelDialog(MainActivity.this);
                                            unFinishTravelDialog.setMessage(getString(R.string.hasInDrivingOrder));
                                            unFinishTravelDialog.setYesOnclickListener("去结算", new UnFinishTravelDialog.onYesOnclickListener() {
                                                @Override
                                                public void onYesClick() {
                                                    if ("-1".equals(response.body().getAttachment().getOrderModel().getUserParkCompensate())) {
                                                        IntentUtils.toCarParkingFeeActivity(mContext, response.body().getAttachment().getOrderId());
                                                    } else {
                                                        IntentUtils.toPaymentActivity(mContext, response.body().getAttachment().getOrderId(), "");
                                                    }
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setNoOnclickListener("取消", new UnFinishTravelDialog.onNoOnclickListener() {
                                                @Override
                                                public void onNoClick() {
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setCancelable(false);
                                            unFinishTravelDialog.show();
                                        }
                                        break;
                                    }
                                }
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ExistingTravel> call, Throwable t) {
                        dismissLoadingDialog();
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "012" + t);
                    }
                });
    }


    //验证用户汽车认证状态

    private void checkUserStatus() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getUserStatus(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<QualificationBean>() {
            @Override
            public void onResponse(Call<QualificationBean> call, Response<QualificationBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    dismissLoadingDialog();
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.REAL_NAME_STATUS, response.body().getAttachment().getIdentityStatus() + "");
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.LICENSE_CAR_STATUS, response.body().getAttachment().getLicenseStatus() + "");
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.DEPOSIT_CAR_STATUS, response.body().getAttachment().getDepositStatus() + "");
                        Intent intent = new Intent(mContext, QualificationActivity.class);
                        switch (response.body().getAttachment().getDepositStatus()) {
                            //保证金
                            case 0:
                                intent.putExtra("SubmitFlag", 3);
                                startActivity(intent);
                                break;
                            case 1:
                                switch (response.body().getAttachment().getIdentityStatus()) {
                                    //身份信息未审核
                                    //身份信息失败
                                    case 10:
                                    case 12:
                                        intent.putExtra("SubmitFlag", 1);
                                        startActivity(intent);
                                        break;
                                    //身份信息审核中
                                    //身份信息审核成功
                                    case 11:
                                    case 13:
                                        switch (response.body().getAttachment().getLicenseStatus()) {
                                            case 10:    //证照未审核
                                            case 12:    //证照失败
                                                intent.putExtra("SubmitFlag", 2);
                                                startActivity(intent);
                                                break;
                                            case 11:    //证照审核中
                                                ToastCompat.makeText(mContext, "您的资格正在审核中...", Toast.LENGTH_SHORT).show();
                                            case 13:    //证照审核成功
                                                break;
                                        }
                                        break;
                                }
                                break;
                        }
                    } else {
                        dismissLoadingDialog();
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<QualificationBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //一键获取附近车辆,弹出网点详情布局
    public void getNearCarOrPark() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getNearCarOrPark(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<NearParkOrCarBean>() {
            @Override
            public void onResponse(Call<NearParkOrCarBean> call, final Response<NearParkOrCarBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        List<ParkDetailBean.AttachmentBean.CarsBean> list = new ArrayList<>();
                        if (response.body().getAttachment().getIsCarOrPark().equals("1")) {//返回的是一个网点
                            NearParkOrCarBean.AttachmentBean.ParksBean
                                    result = response.body().getAttachment().getParks();
                            if (result != null && result.getCarModelList() != null && result.getCarModelList().size() != 0) {
                                //返回最近网点的数据，适配为ParkDetail的Bean，然后获取该网点的第一辆车
                                list = DataBeanConvert.nearParkToPark(result.getCarModelList());
                            }

                        } else if (response.body().getAttachment().getIsCarOrPark().equals("0")) {//返回一个车辆
                            NearParkOrCarBean.AttachmentBean.CarBean nearOneCar = response.body().getAttachment().getCar();
                            if (nearOneCar != null) {
                                //返回最近网点的数据，适配为ParkDetail的Bean，然后获取该网点的第一辆车
                                list = DataBeanConvert.nearCarToPark(nearOneCar);
                            }
                        }

                        final List<ParkDetailBean.AttachmentBean.CarsBean> finalList = list;
                        RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_WALK, curPosition,
                                new LatLng(list.get(0).getLatitude(), list.get(0).getLongitude()), new RoutePlan.OnRoutePlannedListener() {
                                    @Override
                                    public void onRoutePlanSuccess(int distance, int duration) {
                                        DecimalFormat df = new DecimalFormat("0.00");
                                        SharedPreferencesUtils.getInstance(mContext).putStringValue("parkDistance", df.format(distance / 1000.0));
                                        dismissLoadingDialog();
                                        //弹出网点详情布局
                                        layout_no_car.setVisibility(View.GONE);
                                        layout_reserve_order.setVisibility(View.GONE);
                                        layout_reserve_order.setVisibility(View.GONE);
                                        pagerAdapter = new ParkDetailPagerAdapter(mContext, finalList);
                                        pagerParkDetail.setAdapter(pagerAdapter);
                                        choosePosition = 0;
                                        initViewPagerDots(finalList.size());

                                        if (response.body().getAttachment().getIsCarOrPark().equals("0")) {
                                            markerUtils.showParkInfoWindow(R.layout.park_marker_infowindow, finalList.get(0).getTimeStr(),
                                                    new LatLng(finalList.get(0).getLatitude(), finalList.get(0).getLongitude()));
                                        }
                                        park_fee_tips_main.setVisibility(View.VISIBLE);

                                        popCarLayout(layout_park_detail, true);

                                    }

                                    @Override
                                    public void onRoutePlanFailure() {
                                        dismissLoadingDialog();
                                        // tv_address_park.setText("暂无位置信息");
                                    }
                                });


                    } else {
                        dismissLoadingDialog();
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<NearParkOrCarBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                Log.i("netError", "014" + t);
            }
        });
    }

    private void noService() {
        use_car_layout.setVisibility(View.GONE);
        final InCarDialog inCarDialog = new InCarDialog(MainActivity.this);
        inCarDialog.setTitle(getString(R.string.dialogTitle));
        inCarDialog.setMessage(getString(R.string.noOpenCity));
        inCarDialog.setYesOnclickListener("确认", new InCarDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                inCarDialog.dismiss();
            }
        });
        inCarDialog.setNoOnclickListener("取消", new InCarDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                inCarDialog.dismiss();
            }
        });
        inCarDialog.show();
    }

    //获取城市信息
    public void getCityInfo() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getCityInfo(((MyApplication) getApplication()).getRequestFieldMap())
                .enqueue(new Callback<CityDetailBean>() {
                    @Override
                    public void onResponse(Call<CityDetailBean> call, Response<CityDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().getAttachment() != null) {
                            dismissLoadingDialog();
                            if (response.body().getStatus() == 400) {
                                SharedPreferencesUtils.getInstance(mContext).putBooleanValue("isServiceOk", false);
                                noService();  //该城市没有租车服务
                            } else if (response.body().getStatus() == 200) {
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.DEPOSIT_BIKE, response.body().getAttachment().getEnclosure().getBikeBail());
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.DEPOSIT_CAR, response.body().getAttachment().getEnclosure().getCarBail());
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN, response.body().getAttachment().getEnclosure().getAliPay());
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.IS_WXPAY_OPEN, response.body().getAttachment().getEnclosure().getWechatPay());
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.IS_SHARE_INVITE, response.body().getAttachment().getEnclosure().getActUserShare());
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.IS_CAR_PREPARE, response.body().getAttachment().getEnclosure().getActCarPrepare());
                                if (response.body().getAttachment().getEnclosure().getIsCar() == 1) { //汽车服务可用
                                    SharedPreferencesUtils.getInstance(mContext).putBooleanValue("isServiceOk", true);
                                } else {
                                    SharedPreferencesUtils.getInstance(mContext).putBooleanValue("isServiceOk", false);
                                    noService();
                                }
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                            //获取城市围栏
                            initCityBounds();
                            //获取基础配置信息
                            initAppData();
                            //获取弹窗海报
                            getPopPost();
                            //未登录时弹出帮助小绿叶
                            initGreenLeave();
                            clearMap(true);
                            //检查未完成订单
                            if (SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) != null) {  //是否登录
                                hasExistingTravel(); //已登录时获取进行中的行程
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CityDetailBean> call, Throwable t) {
                        dismissLoadingDialog();
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "002");
                    }
                });
    }

    private void initCityBounds() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getFenceList(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<CityBoundBean>() {
            @Override
            public void onResponse(Call<CityBoundBean> call, Response<CityBoundBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        cityBoundsInfo = response.body().getAttachment();
                        if (polygonUtils != null) {
                            polygonUtils.addBounds(cityBoundsInfo);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<CityBoundBean> call, Throwable t) {

            }
        });
    }

    public void getParksAndCars() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getParksAndCars(((MyApplication) getApplication()).getRequestFieldMap())
                .enqueue(new Callback<MapParksAndCarsBean>() {
                    @Override
                    public void onResponse(Call<MapParksAndCarsBean> call, Response<MapParksAndCarsBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                dismissLoadingDialog();
                                //  imageView_refresh.setVisibility(View.GONE);
                                //添加网点和车辆图标
                                carsList = response.body().getAttachment().getCarModels();
                                if ((response.body().getAttachment().getParks() != null && response.body().getAttachment().getParks().size() != 0)
                                        || (carsList != null && carsList.size() != 0)) {
                                    markerUtils.addParksMarker(response.body().getAttachment().getParks(), carsList);
                                }
                            } else {
                                dismissLoadingDialog();
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<MapParksAndCarsBean> call, Throwable t) {
                        dismissLoadingDialog();
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "015" + t);
                    }
                });
    }

    //网点详情
    public void showParkDetailLayout(String parkId, final String parkName,
                                     final LatLng parkPosition) {
        showLoadingDialog("正在规划路线...");
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getParkDetail(((MyApplication) getApplication()).getRequestFieldMap(), parkId)
                .enqueue(new Callback<ParkDetailBean>() {
                    @Override
                    public void onResponse(Call<ParkDetailBean> call, Response<ParkDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                ParkDetailBean.AttachmentBean attachmentBean = response.body().getAttachment();
                                List<ParkDetailBean.AttachmentBean.CarsBean> list = attachmentBean.getCars();
                                final int parkCarsNum = list.size();
                                if (parkCarsNum != 0) {             //有可租车辆，刷新pagerAdapter
                                    list.get(0).setParkName(parkName);
                                    pagerAdapter = new ParkDetailPagerAdapter(mContext, list);
                                    pagerParkDetail.setAdapter(pagerAdapter);
                                    initViewPagerDots(list.size());
                                    choosePosition = 0;
                                }

                                RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_WALK, curPosition,
                                        parkPosition, new RoutePlan.OnRoutePlannedListener() {
                                            @Override
                                            public void onRoutePlanSuccess(int distance, int duration) {
                                                DecimalFormat df = new DecimalFormat("0.00");
                                                SharedPreferencesUtils.getInstance(mContext).putStringValue("parkDistance", df.format(distance / 1000.0));
                                                dismissLoadingDialog();
                                                if (parkCarsNum != 0) {
                                                    park_fee_tips_main.setVisibility(View.VISIBLE);
                                                    if (!layout_park_detail.isShown()) {
                                                        layout_no_car.setVisibility(View.GONE);
                                                        layout_reserve_order.setVisibility(View.GONE);
                                                        popCarLayout(layout_park_detail, true);
                                                    }
                                                } else {
                                                    if (!layout_no_car.isShown()) {
                                                        markerUtils.hideInfoWindow();
                                                        park_fee_tips_main.setVisibility(View.GONE);
                                                        layout_park_detail.setVisibility(View.GONE);
                                                        layout_reserve_order.setVisibility(View.GONE);
                                                        tv_address_no_car.setText(parkName);
                                                        tv_distance_no_car.setText(SharedPreferencesUtils.getInstance(mContext).getStringValue("parkDistance") + "千米");
                                                        popCarLayout(layout_no_car, true);
                                                    } else {
                                                        tv_address_no_car.setText(parkName);
                                                        tv_distance_no_car.setText(SharedPreferencesUtils.getInstance(mContext).getStringValue("parkDistance") + "千米");
                                                    }
                                                }
                                            }

                                            @Override
                                            public void onRoutePlanFailure() {
                                                dismissLoadingDialog();
                                            }
                                        });

                            } else {
                                dismissLoadingDialog();
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ParkDetailBean> call, Throwable t) {
                        dismissLoadingDialog();
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "016" + t);
                    }
                });
    }


    private void showCarDetailLayout(int carMarkerId, final String timeStr, final Marker marker) {
        showLoadingDialog("正在规划路线...");
        final List<ParkDetailBean.AttachmentBean.CarsBean> list = DataBeanConvert.carToPark(carsList.get(carMarkerId));
        pagerAdapter = new ParkDetailPagerAdapter(mContext, list);
        pagerParkDetail.setAdapter(pagerAdapter);
        initViewPagerDots(list.size());
        choosePosition = 0;
        RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_WALK, curPosition,
                marker.getPosition(), new RoutePlan.OnRoutePlannedListener() {
                    @Override
                    public void onRoutePlanSuccess(int distance, int duration) {
                        DecimalFormat df = new DecimalFormat("0.00");
                        SharedPreferencesUtils.getInstance(mContext).putStringValue("parkDistance", df.format(distance / 1000.0));
                        dismissLoadingDialog();
                        markerUtils.showParkInfoWindow(R.layout.park_marker_infowindow, timeStr, marker.getPosition());
                        if (!layout_park_detail.isShown()) {
                            layout_no_car.setVisibility(View.GONE);
                            layout_reserve_order.setVisibility(View.GONE);
                            popCarLayout(layout_park_detail, true);
                            park_fee_tips_main.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onRoutePlanFailure() {
                        tv_distance_no_car.setText("暂无位置信息");
                    }
                });
    }

    //寻电车中订单
    private void loadCarFindLayout(String orderId) {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getTravelDetail(((MyApplication) getApplication()).getRequestFieldMap(), orderId)
                .enqueue(new Callback<TravelDetailBean>() {
                    @Override
                    public void onResponse(Call<TravelDetailBean> call, final Response<TravelDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                isLoadingDone = true;
                                dismissLoadingDialog();
                                TravelDetailBean.AttachmentBean result = response.body().getAttachment();
                                carId = response.body().getAttachment().getCarId() + "";
                                markerUtils.clearParksAndCarsMarker();
                                markerUtils.addOneCar(result.getCarModel().getLatitude(), result.getCarModel().getLongitude());

                                String userRemark = response.body().getAttachment().getCarModel().getUserRemark();
                                LatLng carPosition = new LatLng(result.getCarModel().getLatitude(), result.getCarModel().getLongitude());
                                RoutePlan.getInstance().clearRoutePlanning();
                                RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_WALK, curPosition, carPosition, null);

                                GeoCoderUtils.getInstance().reverseGeoCode(carPosition, new GeoCoderUtils.OnGeoListener() {
                                    @Override
                                    public void onGeoSuccess(String address) {
                                        tx_place_order_position.setText(address);
                                    }

                                    @Override
                                    public void onGeoFailure() {
                                        tx_place_order_position.setText("地址获取失败");
                                    }
                                });
                                tv_place_order_remark.setText(userRemark);

                                reLoadCarFindLayout(result.getCarModel().getPicture(),
                                        result.getCarModel().getBrand() + result.getCarModel().getModel(),
                                        result.getCarModel().getLicenseTag(), result.getOverplusTime() * 1000);
                            } else {
                                dismissLoadingDialog();
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<TravelDetailBean> call, Throwable t) {
                        dismissLoadingDialog();
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "017" + t);
                    }
                });
    }


    //寻车
    public void findCar(String orderId, String carId) {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).findCar(((MyApplication) getApplication()).getRequestFieldMap(), orderId, carId).enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        dismissLoadingDialog();
                    } else {
                        dismissLoadingDialog();
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastCompat.makeText(mContext, getResources().getString(R.string.findCarFailure), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * app重启电车寻车中
     *
     * @param placeOrderTimer 下单倒计时
     */
    private void reLoadCarFindLayout(String pictureId, String carBrand, String carLicense,
                                     long placeOrderTimer) {
        tx_place_order_brand.setText(carBrand);
        tx_place_order_plate.setText(carLicense);
        this.carLicense = carLicense;
        layout_park_detail.setVisibility(View.GONE);
        popCarLayout(layout_reserve_order, true);
        ImageLoader.getInstance().displayImage(getApplicationContext(), ((MyApplication) getApplication()).getImageUrl() + pictureId, iv_order_car);
        findCarTimer(placeOrderTimer);
    }

    //寻车倒计时
    private void findCarTimer(final long placeOrderTimer) {
        timer = new CountDownTimer(placeOrderTimer, 1000) {
            @Override
            public void onTick(long l) {//15min
                tx_place_order_remind1.setText("预约中，");
                tx_reserve_order_timer.setText(TimeUtils.formatSecond(l / 1000 + ""));
                tx_place_order_remind2.setText("后自动取消");
            }

            @Override
            public void onFinish() {
                checkCarOrderStatus();
            }
        };
        timer.start();
        acquireWakeLock();
    }

    //倒计时结束时，从服务器查询订单状态(订单是否真正超时)
    private void checkCarOrderStatus() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).checkAutoCancel(((MyApplication) getApplication()).getRequestFieldMap(), orderId).enqueue(new Callback<CheckCarOrderBean>() {
            @Override
            public void onResponse(Call<CheckCarOrderBean> call, final Response<CheckCarOrderBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment().getOrderStatus() == 103) {
                            timer.cancel();
                            timer = null;
                            releaseWakeLock();
                            mapStatusUtils.clearMap();
                            RoutePlan.getInstance().clearRoutePlanning();
                            getParksAndCars();
                            popCarLayout(layout_reserve_order, false);
                        } else if (response.body().getAttachment().getOrderStatus() == 0) {
                            timer.cancel();
                            findCarTimer(response.body().getAttachment().getOverplusTime() * 1000);
                        }
                    } else {
                        timer.cancel();
                        timer = null;
                        releaseWakeLock();
                        mapStatusUtils.clearMap();
                        RoutePlan.getInstance().clearRoutePlanning();
                        getParksAndCars();
                        popCarLayout(layout_reserve_order, false);
                    }
                }
            }

            @Override
            public void onFailure(Call<CheckCarOrderBean> call, Throwable t) {

            }
        });
    }

    //开车门
    public void openCarDoor(final String orderId, final String carId) {
        showLoadingDialog();

        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).openCar(((MyApplication) getApplication()).getRequestFieldMap(), orderId, carId, "0").enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        Intent intent = new Intent(mContext, DrivingActivity.class);
                        intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                        intent.putExtra("carId", carId);
                        intent.putExtra("parkId", parkId);
                        //停止计时器
                        if (timer != null) {
                            timer.cancel();
                            timer = null;
                            releaseWakeLock();
                        }
                        dismissLoadingDialog();
                        //下单寻车布局消失
                        layout_reserve_order.setVisibility(View.GONE);
                        setAnimator(layout_park_detail, 0f, 200f, 500L, false);
                        startActivity(intent);
                    } else {
                        dismissLoadingDialog();
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastCompat.makeText(mContext, getResources().getString(R.string.openCarDoorFailure), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //取消电车订单
    public void cancelCarOrder(final String orderId) {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).cancelOrder(((MyApplication) getApplication()).getRequestFieldMap(), orderId).enqueue(new Callback<CancelOrder>() {
            @Override
            public void onResponse(Call<CancelOrder> call, Response<CancelOrder> response) {
                if (response.isSuccessful() && response.body() != null) {
                    dismissLoadingDialog();
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment().getOrders().getStatus() == 102) {
                            ToastCompat.makeText(mContext, getResources().getString(R.string.cancelOrderSuccess), Toast.LENGTH_SHORT).show();
                            timer.cancel();
                            timer = null;
                            popCarLayout(layout_reserve_order, false);
                            releaseWakeLock();
                            mapStatusUtils.clearMap();
                            RoutePlan.getInstance().clearRoutePlanning();
                            getParksAndCars();

                        } else if (response.body().getAttachment().getOrders().getStatus() == 16 || response.body().getAttachment().getOrders().getStatus() == 17) {
                            timer.cancel();
                            timer = null;
                            releaseWakeLock();
                            IntentUtils.toPaymentActivity(mContext, orderId, "");
                        }
                        mapStatusUtils.animateMove(curPosition, 18, 600);
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CancelOrder> call, Throwable t) {
                dismissLoadingDialog();
                ToastCompat.makeText(mContext, getResources().getString(R.string.cancelOrderFailure), Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * @param view
     * @param isAppear 电车的布局显示 隐藏
     */
    private void popCarLayout(View view, boolean isAppear) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        layoutHeight = DensityUtils.px2dp(mContext, view.getMeasuredHeight());

        Log.i("layoutHeightCar", layoutHeight + "");
        if (view == layout_no_car || view == layout_reserve_order) {
            if (isAppear) {
                setAnimator(view, layoutHeight, 0f, 500L, true);
                setAnimator(imageView_locate, 0f, -(layoutHeight - 21), 500L, true);
                imageView_refresh.setVisibility(View.GONE);
                //setAnimator(imageView_refresh, 0f, -(layoutHeight), 500L, true);
            } else {
                setAnimator(imageView_locate, -(layoutHeight - 21), 0f, 500L, false);
                imageView_refresh.setVisibility(View.VISIBLE);
                //setAnimator(imageView_refresh, -(layoutHeight), 0f, 500L, false);
                setAnimator(view, 0f, layoutHeight, 500L, false);
            }
        } else {
            if (android.os.Build.VERSION.SDK_INT == 19) {
                layoutHeight += DensityUtils.dp2px(mContext, 15);
            }
            if (isAppear) {
                setAnimator(view, layoutHeight, 0f, 500L, true);
                setAnimator(imageView_locate, 0f, -(layoutHeight - 21), 500L, true);
                imageView_refresh.setVisibility(View.GONE);
                //setAnimator(imageView_refresh, 0f, -(layoutHeight - 50), 500L, true);
            } else {
                setAnimator(imageView_locate, -(layoutHeight - 21), 0f, 500L, false);
                imageView_refresh.setVisibility(View.VISIBLE);
                //setAnimator(imageView_refresh, -(layoutHeight - 50), 0f, 500L, false);
                setAnimator(view, 0f, layoutHeight, 500L, false);
            }
        }
    }


    /*   //弹窗动画消失后后回调
       @Subscribe
       public void AnimalEvent(AnimalEvent event) {
           if (event.finish) {
               animSet.start();
           }
       }
   */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //确认租用电车页面返回
        if (requestCode == Constants.REQUEST_RENT && resultCode == Constants.RESULT_RENT) {
            String carBrand = data.getStringExtra("carBrand");
            String carPlate = data.getStringExtra("carPlate");
            orderId = data.getStringExtra(IntentKey.INTENT_ORDER_ID);
            carId = data.getStringExtra("carId");
            parkId = data.getStringExtra("parkId");
            String pictureId = data.getStringExtra("picture");
            String carLatitude = data.getStringExtra("carLatitude");
            String carLongitude = data.getStringExtra("carLongitude");
            long overplusTime = data.getLongExtra("overplusTime", 0);
            String userRemark = data.getStringExtra("userRemark");
            mapStatusUtils.clearMap();
            park_fee_tips_main.setVisibility(View.GONE);
            markerUtils.addOneCar(Double.parseDouble(carLatitude), Double.parseDouble(carLongitude));
            RoutePlan.getInstance().clearRoutePlanning();
            RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_WALK, curPosition,
                    new LatLng(Double.parseDouble(carLatitude), Double.parseDouble(carLongitude)), null);
            GeoCoderUtils.getInstance().reverseGeoCode(new LatLng(Double.parseDouble(carLatitude), Double.parseDouble(carLongitude)),
                    new GeoCoderUtils.OnGeoListener() {
                        @Override
                        public void onGeoSuccess(String address) {
                            tx_place_order_position.setText(address);
                        }

                        @Override
                        public void onGeoFailure() {
                            tx_place_order_position.setText("地址获取失败");
                        }
                    });

            tv_place_order_remark.setText(userRemark);
            reLoadCarFindLayout(pictureId, carBrand, carPlate, overplusTime * 1000);
            //开启定位服务返回结果
        } else if (requestCode == Constants.REQUEST_Location_Service) {
            initLocationService();
        }
    }

    @Override
    protected void onResume() {
        use_car_layout.setVisibility(View.VISIBLE);
        mapView.onResume();
        if (!isFirstLocation) {
            startLocation();
        }
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
        //刷新地图图标
        if (!isFirstInMain && curPosition != null && !layout_reserve_order.isShown() && !layout_park_detail.isShown()
                && !layout_no_car.isShown()) {
            getParksAndCars();
        }

        if (((MyApplication) getApplication()).getUid() != null) {
            getTopMes();
            getMsgRed();
        }

        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        super.onResume();
    }


    @Override
    protected void onPause() {
        if (SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) == null) {
            use_car_layout.setVisibility(View.GONE);
        }
        mLocClient.stop();
        mapView.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        super.onPause();
    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }


    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        MapView.setMapCustomEnable(false);
        mapView.onDestroy();
        mapView = null;
        super.onDestroy();
    }


    /**
     * @param view     控件
     * @param isAppear 出现或消失
     */
    private void setAnimator(final View view, float start, float end, long duration,
                             boolean isAppear) {
        ObjectAnimator animator;
        animator = ObjectAnimator.ofFloat(view, "translationY", DensityUtils.dp2px(mContext, start), DensityUtils.dp2px(mContext, end));
        animator.setDuration(duration);
        if (isAppear) {
            view.setVisibility(View.VISIBLE);
        } else {

            if (view == layout_park_detail || view == layout_no_car || view == layout_reserve_order) {
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {
                        isAnimatorShow = true;
                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        isAnimatorShow = false;
                        layout_park_detail.setVisibility(View.GONE);
                        layout_no_car.setVisibility(View.GONE);
                        layout_reserve_order.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {
                    }
                });
            }
        }
        animator.start();
    }

    //返回键弹出布局消失，按两次退出应用
    @Override
    public void onBackPressed() {
        backPress(true);
    }

    private void backPress(boolean isExit) {
        if (!isAnimatorShow && (layout_no_car.isShown() || layout_park_detail.isShown())) {
            if (layout_no_car.isShown()) {
                popCarLayout(layout_no_car, false);
                RoutePlan.getInstance().clearRoutePlanning();
                markerUtils.hideInfoWindow();
                if (curPosition != null) {
                    mapStatusUtils.animateMove(curPosition, 18, 600);
                }
                return;
            } else if (layout_park_detail.isShown()) {
                popCarLayout(layout_park_detail, false);
                park_fee_tips_main.setVisibility(View.GONE);
                RoutePlan.getInstance().clearRoutePlanning();
                markerUtils.hideInfoWindow();
                if (curPosition != null) {
                    mapStatusUtils.animateMove(curPosition, 18, 600);
                }
                return;
            }
        } else if (isExit) {
            exit();
        }
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastCompat.makeText(this, "再按一次退出大道用车", Toast.LENGTH_SHORT).show();
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            if (timer != null) {
                timer.cancel();
                timer = null;
                releaseWakeLock();
            }
            //mapUtils.clearCoverPolygon();
            AppManager.getAppManager().AppExit(mContext);
            ((MyApplication) getApplication()).setTripMode(-1);
        }
    }

    /**
     * isContinue
     * 不传或者为false：保持离开MainActivity时的状态;
     * true: MainActivity页面的内容重置，此时如果isLogin为true,检查未完成订单，initApp();
     * <p>
     * <p>
     * chooseCar
     * 不传或者为false: 不执行动作
     * true: WebView中点击"我要用车"跳转来，切换至汽车，跳出资格认证流程
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra("isContinue", false)) {            //继续跳转之前的步骤

        } else if (intent.getBooleanExtra("chooseCar", false)) {  //WebView"我要用车"跳转来
            if (((MyApplication) getApplication()).getTripMode() == 2 && (((MyApplication) getApplication()).getTripAvai() == 3 || ((MyApplication) getApplication()).getTripAvai() == 1)) {
                clearMap(true);
                ((MyApplication) getApplication()).setTripMode(1);
                setAnimator(imageView_locate, 0, 0f, 500L, false);
                imageView_refresh.setVisibility(View.VISIBLE);
                //setAnimator(imageView_refresh, 0, 0f, 500L, false);
                if (timer != null) {
                    timer.cancel();
                    releaseWakeLock();
                }
            }
            checkUserStatus();

        } else {    //不继续跳转之前的步骤
            imageView_help.setVisibility(View.GONE);
            mes_red_hot.setVisibility(View.GONE);
            if (intent.getBooleanExtra("isLogin", false)) {  //登录后检 查订单状态, 检查true,不检查不传或为false
                isLoadingDone = false;
                hasExistingTravel();
            } else {
                clearMap(true);
                setAnimator(imageView_locate, 0, 0f, 500L, false);
                imageView_refresh.setVisibility(View.VISIBLE);
                //setAnimator(imageView_refresh, 0, 0f, 500L, false);
                if (timer != null) {
                    timer.cancel();
                    releaseWakeLock();
                }
            }
        }
    }

    // 小绿叶
    private void initGreenLeave() {
        //显示使用帮助 小绿叶
        if (SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) == null) {
            imageView_help.setVisibility(View.VISIBLE);
            /*ObjectAnimator animator = ObjectAnimator.ofFloat(imageView_help, "translationY", DensityUtils.dp2px(mContext, 0), DensityUtils.dp2px(mContext, 173));
            animator.setDuration(800).setInterpolator(new BounceInterpolator());
            animator.start();*/
        }
    }


    private void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService");
            if (null != wakeLock) {
                wakeLock.acquire();
            }
        }
    }


    //释放设备电源锁
    private void releaseWakeLock() {
        if (null != wakeLock) {
            wakeLock.release();
            wakeLock = null;
        }
    }


    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            if (curPosition != null) {
                locData = new MyLocationData.Builder()
                        .accuracy(mCurrentAccracy)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(mCurrentDirection).latitude(curPosition.latitude)
                        .longitude(curPosition.longitude).build();
                mBaiduMap.setMyLocationData(locData);
            }
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null || mapView == null) {
                dismissLoadingDialog();
                new AlertDialog.Builder(mContext).setTitle("大道用车提示").setMessage("定位异常，请退出应用再试。")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                AppManager.getAppManager().AppExit(mContext);
                            }
                        }).setCancelable(false).show();
                return;
            }

            locationErrorCode = bdLocation.getLocType();
            if (locationErrorCode == BDLocation.TypeGpsLocation || locationErrorCode == TypeNetWorkLocation) {//GPS或者网络定位成功
                Log.i("curPositionMain", "纬度" + bdLocation.getLatitude() + "经度" + bdLocation.getLongitude()
                        + "citycode" + bdLocation.getCityCode() + "countrycode" + bdLocation.getCountryCode());
                bdLocation = LocationFilter.Algorithm(bdLocation);//根据历史定位，对定位的结果平滑过滤
                curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位
                ((MyApplication) getApplication()).setCurPosition(curPosition.latitude + "", curPosition.longitude + "");
                address = bdLocation.getAddress().address;
                mCurrentAccracy = bdLocation.getRadius();
                locData = new MyLocationData.Builder()
                        .accuracy(mCurrentAccracy)
                        .direction(bdLocation.getDirection())// 此处设置开发者获取到的方向信息，顺时针0-360
                        .latitude(curPosition.latitude)
                        .longitude(curPosition.longitude).build();

                mBaiduMap.setMyLocationData(locData);
                if (isFirstLocation) {//首次成功的定位
                    isFirstLocation = false;
                    mapStatusUtils.animateMove(curPosition, 18, 400);
                    if (bdLocation.getCityCode() != null && !bdLocation.getCityCode().equals("")) {
                        ((MyApplication) getApplication()).setAreaCode(bdLocation.getCityCode());
                        ((MyApplication) getApplication()).setAdCode(bdLocation.getCityCode());
                        getCityInfo();//获取城市信息
                    }
                }

            } else {//定位失败
                Log.i("loctionerror", bdLocation.getLocType() + "");
                if (isFirstLocationError && isFirstLocation) {  //第一次定位失败执行，之后的失败定位不再执行
                    dismissLoadingDialog();
                    isFirstLocationError = false;
                    if (locationErrorCode == TypeServerError) {  //缺少定位权限
                        new AlertDialog.Builder(mContext).setTitle("大道用车提示").setMessage("您可能拒绝了定位权限，请在设置中开启权限。")
                                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        intent.setData(Uri.parse("package:" + getPackageName()));
                                        startActivity(intent);
                                    }
                                }).setCancelable(false).show();
                    } else if (locationErrorCode == TypeNetWorkException || locationErrorCode == TypeCriteriaException) {
                        new AlertDialog.Builder(mContext).setTitle("大道用车提示").setMessage("定位失败，您的网络似乎不太畅通。")
                                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                        startActivity(intent);
                                    }
                                }).setCancelable(false).show();
                    } else {
                        new AlertDialog.Builder(mContext).setTitle("大道用车提示").setMessage("定位失败，请检查定位服务是否开启，网络是否正常。")
                                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                        startActivity(intent);
                                    }
                                }).setCancelable(false).show();
                    }
                }
            }
        }

    }

    /**
     * 清除主页面的地图和选车等布局
     */
    private void clearMap(boolean isLoadMarker) {
        mapStatusUtils.animateMove(curPosition, 18, 600);
        layout_park_detail.setVisibility(View.GONE);
        layout_reserve_order.setVisibility(View.GONE);
        layout_no_car.setVisibility(View.GONE);
        markerUtils.hideInfoWindow();
        park_fee_tips_main.setVisibility(View.GONE);
        mapStatusUtils.clearMap();
        //清除普通车路线规划
        RoutePlan.getInstance().clearRoutePlanning();
        if (isLoadMarker) {
            getParksAndCars();
        }
    }

    private void startLocation() {
        mLocClient.start();
    }
}